#Metabolic COmparisons
library(readxl)
library(tidyverse)

Theme = theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank(),axis.title=element_text(size=20),axis.text=element_text(size=18))

#Load Data
Data = read_csv("Data/Repeats20.csv")
Field = read_xlsx("Data/Field Data Volumes and Mass.xlsx")


#Prep Data
Data$ID<- as.character(with(Data, paste0(Day,ScaleID)))
Data$MR=-Data$MR
Data$MR2=-Data$MR2
#remove outliers
Data=subset(Data, MR2<1)



########Within Field variation



###Coefficent of variation
Data2 = Data%>%
  dplyr::group_by(ID) %>%
  summarise(SD=sd(MR2),AV = mean(MR2))

Data2$Coef = Data2$SD/Data2$AV
Data2$Coef2 = Data2$SD/Data2$AV*100
mean(na.omit(Data2$Coef2))

hist(Data2$Coef,breaks=20)
t.test(Data2$Coef)#does not overlap zero

Data=merge(Data,Data2, by=c("ID"))

#Change Data
Data$Day=as.character(Data$Day)
Data$Run=as.character(Data$Run)


###Better ICC
library(rptR)
r1 = rpt((MR) ~ log(Weight)+(Temp)+(1 | ID)+Run+Day, grname = c("ID"), data = Data, datatype = "Gaussian", 
         nboot = 1000, npermut = 0)#Main
print(r1)
summary(r1)
VarCorr(r1)
plot(r1)



model <- lmer(log(MR) ~ log(Weight) + Temp + Run + Day + (1 | ID), data = Data)
VarCorr(model)
#Effect sizes
sd_between <- 0.16191
sd_within  <- 0.30341

var_between <- sd_between^2
var_within  <- sd_within^2
# Number of repeats per individual
n_rep <- 4

var_eff <- var_between + (var_within / n_rep)
sd_eff  <- sqrt(var_eff)

#Function
sample_size <- function(delta, sd, alpha = 0.05, power = 0.8) {
  z_alpha <- qnorm(1 - alpha/2)
  z_beta  <- qnorm(power)
  
  n <- 2 * (z_alpha + z_beta)^2 * sd^2 / delta^2
  return(ceiling(n))  # round up
}

d_vals <- c(0.8, 0.5)
delta_vals <- d_vals * sd_eff

n_per_group_d <- sapply(delta_vals, sample_size, sd = sd_eff)

###COmpare CoV and Repeatability of RMR



###Variation in RMR
RA = read.csv("Data/Lab Repeats/RMRRep_A")
RB = read.csv("Data/Lab Repeats/RMRRep_B")
RC = read.csv("Data/Lab Repeats/RMRRep_C")
RD = read.csv("Data/Lab Repeats/RMRRep_D")
RE = read.csv("Data/Lab Repeats/RMRRep_E")
RF = read.csv("Data/Lab Repeats/RMRRep_F")
RG = read.csv("Data/Lab Repeats/RMRRep_G")
RH = read.csv("Data/Lab Repeats/RMRRep_H")
RI = read.csv("Data/Lab Repeats/RMRRep_I")

RMRr = rbind(RA,RB,RC,RD,RE,RF,RG,RH,RI)
RMRr=RMRr[,-1]
RMRr = merge(RMRr, Field, id=c("id"))
RMRr = subset(RMRr, SP=="Trout")

RMRr2 = RMRr%>%
  group_by(ID) %>%
  summarise(SD=sd(RMRRep),AV = -mean(RMRRep))
sd(RMRr$RMRRep)

RMRr2$Coef = RMRr2$SD/RMRr2$AV
RMRr2$Coef2 = RMRr2$SD/RMRr2$AV*100
mean(RMRr2$Coef2)
hist(RMRr2$Coef,breaks=10)
hist(Data2$Coef,breaks=10)
shapiro.test(Data2$Coef)
shapiro.test(RMRr2$Coef)

t.test(RMRr2$Coef, unique(Data2$Coef))
t.test(RMRr2$Coef, unique(Data$Coef)[seq(1:15)])
wilcox.test(RMRr2$Coef, unique(Data$Coef))
boxplot(RMRr2$Coef,unique(Data$Coef))


#Restructure
Var1 = dplyr::select(RMRr2, ID, Coef)
Var1$Method="RMR^L"
Var2 = dplyr::select(Data, ID, Coef)
Var2$Method="RMR^F"
Var=rbind(Var1,unique(Var2))
p=ggplot(Var, aes(y=Coef,x=Method))+geom_boxplot(outliers= FALSE)+geom_point(alpha=0.5,size=2)+theme_bw()+Theme+ylab("Coefficent of Variation")+ scale_x_discrete(
  labels = c(
    "RMR^L" = bquote(RMR[L]),
    "RMR^F" = bquote(RMR[F])
  ))+ylim(0,0.7)

ggsave("C:/Users/peter/OneDrive/Life/Marine Biology/PhD Metabolic Drivers of Growth and Survival in Salmonids/Chapters/Papers/Chapter 1 Method Validation/Data/Data Analysis/Plots/Coef of Var.tiff", plot = p, width = 4, height = 4, units = "in", dpi = 300)



#GLS
library(nlme)
Var=na.omit(Var)
gls_model <- gls(Coef ~ Method, data = Var, 
                 weights = varIdent(form = ~ 1 | Method))
summary(gls_model)

#Check
E1 = resid(gls_model, type ="pearson")
F1=fitted(gls_model)
eta=predict(gls_model, type="link")
plot(x=F1,y=E1)
abline(h=0,v=0,lty=2)
plot(x=eta,y=E1)
boxplot(E1~Var$Method)
acf(resid(gls_model), main = "ACF of Residuals")
qqnorm(residuals(gls_model))
qqline(residuals(gls_model))
ranef(gls_model)

#Plot properly
Theme = theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank(),axis.title=element_text(size=20),axis.text=element_text(size=18))

ggplot()+geom_boxplot(aes(y=RMRr2$Coef,x="RMR"))+geom_point(aes(y=RMRr2$Coef,x="RMR"))+geom_boxplot(aes(y=Data$Coef,x="RMRr"))+geom_point(aes(y=Data$Coef,x="RMRr"))+theme_bw()+Theme+theme(legend.position = 0)+
  ylab(expression(paste("Coefficent of variation")))+scale_x_discrete(labels=c("RMR",expression(RMR[F])))+xlab("Method")

#RPT
RMRr$RMR2 = -RMRr$RMRRep*RMRr$Weight

#r2 = rpt((RMRRep) ~ (1 | ID), grname = c("ID"), data = RMRr, datatype = "Gaussian", 
#         nboot = 1000, npermut = 0)
r2 = rpt((RMR2) ~ log(Weight)+(1 | ID), grname = c("ID"), data = RMRr, datatype = "Gaussian", 
         nboot = 1000, npermut = 0)
print(r2)
summary(r2)
plot(r2)
plot(r2, type = "permut", cex.main = 1)

#Vs SMR
RA = read.csv("SMRRep_A")
RB = read.csv("SMRRep_B")
RC = read.csv("SMRRep_C")
RD = read.csv("SMRRep_D")
RE = read.csv("SMRRep_E")
RF = read.csv("SMRRep_F")
RG = read.csv("SMRRep_G")
RH = read.csv("SMRRep_H")
RI = read.csv("SMRRep_I")

SMRr = rbind(RA,RB,RC,RD,RE,RF,RG,RH,RI)
SMRr=SMRr[,-1]
SMRr = merge(SMRr, Field, id=c("id"))
SMRr = subset(SMRr, SP=="Trout")
SMRr$SMR2 = -SMRr$SMRRep*SMRr$Weight

r2 = rpt((SMR2) ~ log(Weight)+(1 | ID), grname = c("ID"), data = SMRr, datatype = "Gaussian", 
         nboot = 1000, npermut = 0)
print(r2)
summary(r2)
plot(r2)

